<?php

class ModelDefinition
{
	var $table_name;
	var $config = array(
		// suppression passive (active BOOLEAN)
		'restorable' => false,
		// date de création/mise à jour de l'objet (created_at DATETIME, updated_at DATETIME)
		'timestamps' => false
	);

	function ModelDefinition($table_name)
	{
		$this->table_name = $table_name;
	}
}

abstract class BaseModel extends Model
{
	// model definition access -------------------------------------------------

	protected abstract function get_definition();

	private function table_name()
	{
		return $this->get_definition()->table_name;
	}

	private function config($key)
	{
		return $this->get_definition()->config[$key];
	}

	// model manipulation ------------------------------------------------------

	function BaseModel()
	{
		parent::Model();
	}

	/**
	 * Save object in DB
	 * If the object already exists, the record is updated, else a new record is created
	 */
	function save($object)
	{
		$result = false;
		if ($object->id == null) {
			// INSERT
			if ($this->config('timestamps')) {
				$object->created_at = $object->updated_at = date_db_format();
			}
			$result = $this->db->insert($this->table_name(), $object);
			$object->id = $this->db->insert_id(); // retrieve new object id
		}
		else {
			// UPDATE
			if ($this->config('timestamps')) {
				$object->updated_at = date_db_format();
			}
			$this->db->where('id', $object->id);
			$result = $this->db->update($this->table_name(), $object);
		}
		return $result;
	}

	/**
	 * Suppression de l'objet
	 * @param id: object id to be deleted
	 */
	function delete($id)
	{
		if ($this->config('restorable')) {
			return $this->db->update($this->table_name(), array('active' => 0), 'id = '.intval($id));
		}
		$this->destroy($id);
	}

	/**
	 * Suppression définitive de l'objet
	 * @param id: object id to be deleted
	 */
	function destroy($id)
	{
		return $this->db->delete($this->table_name(), array('id' => $id));
	}

	/**
	 * Restaurer un objet supprimé
	 * @param id: object id to be restored
	 */
	function restore($id)
	{
		if ($this->config('restorable')) {
			return $this->db->update($this->table_name(), array('active' => 1), 'id = '.intval($id));
		}
		throw new Exception('[ModelException] objects '.$this->table_name().' are not restorable');
	}
}
